package aps.module_Core;

//Java
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

//Minecraft
import net.minecraft.src.Packet250CustomPayload;
import net.minecraft.src.INetworkManager;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.TileEntity;

//FML
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;

import aps.module_Machines.TileEntityEnergyDirector;
import aps.module_Machines.TileEntityEnergyStore;
//Buildcraft
import buildcraft.core.network.PacketUpdate;

public class APSPacketHandler implements IPacketHandler {

	public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player)
	{
		//get data
		DataInputStream data = new DataInputStream(new ByteArrayInputStream(packet.data));
		
		//process
		try {
			int packetID = data.read();
			switch (packetID)
			{
				//update energy redirector block
				case APSPacketIDs.UPDATE_ENERGYREDIRECTOR: 
					PacketUpdate packetR = new PacketUpdate();
					packetR.readData(data);
					onUpdateEnergyRedirector((EntityPlayer)player, packetR);
					break;
				case APSPacketIDs.UPDATE_ENERGYSTORE:
					PacketUpdate packetS = new PacketUpdate();
					packetS.readData(data);
					onUpdateEnergyStore((EntityPlayer)player, packetS);
					break;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void onUpdateEnergyRedirector(EntityPlayer player, PacketUpdate packet)
	{
		if (!player.worldObj.blockExists(packet.posX, packet.posY, packet.posZ))
			return; //doesnt exist
		
		if (!(player.worldObj.getBlockTileEntity(packet.posX, packet.posY, packet.posZ) instanceof TileEntityEnergyDirector))
			return; //not an energy director
		
		TileEntityEnergyDirector tile = (TileEntityEnergyDirector)player.worldObj.getBlockTileEntity(packet.posX, packet.posY, packet.posZ);
		
		TileEntityEnergyDirector.UpdateMessage message = new TileEntityEnergyDirector.UpdateMessage();
		TileEntityEnergyDirector.updateMessageWrapper.fromPayload(message, packet.payload);
		tile.handleUpdateMessage(message);
	}
	
	private void onUpdateEnergyStore(EntityPlayer player, PacketUpdate packet)
	{
		if (!player.worldObj.blockExists(packet.posX, packet.posY, packet.posZ))
			return; //doesnt exist
		
		if (!(player.worldObj.getBlockTileEntity(packet.posX, packet.posY, packet.posZ) instanceof TileEntityEnergyStore))
			return; //not an energy store
		
		TileEntityEnergyStore tile = (TileEntityEnergyStore)player.worldObj.getBlockTileEntity(packet.posX, packet.posY, packet.posZ);
		
		TileEntityEnergyStore.UpdateMessage message = new TileEntityEnergyStore.UpdateMessage();
		TileEntityEnergyStore.updateMessageWrapper.fromPayload(message, packet.payload);
		tile.handleUpdateMessage(message);
	}
}
